package com.cwt_taxi_xa.record;

import java.io.File;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.db.dal.DBConstants;
import com.cwt_taxi_xa.db.dal.DBOpenHelper;
import com.cwt_taxi_xa.model.RecorderInfo;
import com.cwt_taxi_xa.protocol.EncoderUtil;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.FileOper;
import com.cwt_taxi_xa.util.StringUtil;

/**
 * 录音数据本地保存
 * @author wlh
 *
 */
public class RecorderDao {

	private DBOpenHelper helper;
	private ContentValues values;
	private static final String TAG = "RecordingDao";

	public RecorderDao(Context context) {
		super();
		helper = new DBOpenHelper(context);
		values = new ContentValues();
	}

	/**
	 * 保存数据
	 * @param info
	 * @return rowId 如果rowId ！= -1，则保存成功
	 */
	public synchronized long save(RecorderInfo info) {
		try {
			String mediaId = info.getMediaId();
			SQLiteDatabase db = helper.getWritableDatabase();

			// 检测录音文件是否大于500M
			final File file = new File(Constants.RECORDING_PATH);
			long size = FileOper.getFileListSize(file) / 1024 / 1024;
			AppLog.i(TAG, "录音，文件夹大小："+size);
			if(file.exists() && size > Constants.recordMaxSize){
				deleteFirstInfo(db);
			}

			// 存储新的录音文件
			long rowId = -1;
			values.clear();
			values.put(DBConstants.REC_MEDIA_ID, mediaId);
			values.put(DBConstants.REC_TIME, info.getTime());
			values.put(DBConstants.REC_REASON, info.getReason());
			values.put(DBConstants.REC_START_LAT, info.getsLat());
			values.put(DBConstants.REC_START_LNG, info.getsLng());
			rowId = db.insert(DBConstants.TABLE_RECORDING, null, values);
			db.close();
			AppLog.i(TAG, "插入一条录音数据，rowId："+rowId);
			return rowId;
		} catch (Exception e) {
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return -1;
		}
	}

	/**
	 * 循环删除第一条信息
	 * @return locationInfos 所有数据
	 */
	public synchronized void deletefullInfos() {
		// TODO Auto-generated method stub
		try {
			SQLiteDatabase db = helper.getWritableDatabase();
			//			db.beginTransaction();

			// 检测录音文件是否大于500M
			final File file = new File(Constants.RECORDING_PATH);
			long size = FileOper.getFileListSize(file) / 1024 / 1024;
			AppLog.i(TAG, "录音，文件夹大小："+size);
			if(file.exists()){
				while(size > Constants.recordMaxSize){
					Cursor c = db.query(DBConstants.TABLE_RECORDING, null, null,
							null, null, null, null);
					if(c != null && c.moveToFirst()){
						int id = c.getInt(c.getColumnIndex(DBConstants.REC_ID));
						String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
						int result = db.delete(DBConstants.TABLE_RECORDING,
								DBConstants.REC_ID+"=?", new String[]{String.valueOf(id)});
						AppLog.i(TAG, "删除第一条数据：result = "+result + "; id = "+id + "; file = "+time);
						deletePhoto(time);
						size = FileOper.getFileListSize(file) / 1024 / 1024;
						AppLog.i(TAG, "录音，文件夹大小："+size);
					}
				}
			}
			//设置事务标志为成功，当结束事务时就会提交事务
			/*db.setTransactionSuccessful();
			db.endTransaction();*/
			db.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
	}

	/**
	 * 删除第一条信息
	 * @return locationInfos 所有数据
	 */
	public synchronized void deleteFirstInfo(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		try {
			Cursor c = db.query(DBConstants.TABLE_RECORDING, null, null,
					null, null, null, null);
			if(c != null && c.moveToFirst()){
				int id = c.getInt(c.getColumnIndex(DBConstants.REC_ID));
				String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
				int result = db.delete(DBConstants.TABLE_RECORDING,
						DBConstants.REC_ID+"=?", new String[]{String.valueOf(id)});
				AppLog.i(TAG, "删除第一条数据：result = "+result + "; id = "+id + "; file = "+time);
				deletePhoto(time);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
	}

	/**
	 * 获取数据总条数
	 * @param db2
	 * @return count 总条数 count != -1：成功
	 */
	public synchronized int getCount(SQLiteDatabase db){
		int count = -1;
		Cursor c = db.query(DBConstants.TABLE_RECORDING, null, null, null, null, null,null);
		if(c != null){
			count = c.getCount();
		}
		return count;
	}

	/**
	 * 清空表数据
	 * @return result != -1：成功
	 */
	public synchronized int clearTable(){
		try {
			int result = -1;
			SQLiteDatabase db = helper.getWritableDatabase();
			result = db.delete(DBConstants.TABLE_RECORDING, null, null);
			//		db.execSQL("delete from sqlite_sequence where name = \"" + Constants.TABLENAME+ "\"");
			db.execSQL("update sqlite_sequence set seq = 0 where name = \""+ DBConstants.TABLE_RECORDING+ "\"");
			db.close();
			AppLog.i(TAG, "清空表数据,result:"+result);
			return result;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
			return -1;
		}
	}

	public synchronized int getCount() {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		int count = getCount(db);
		db.close();
		if(SystemRecord.isRecording){
			count = count - 1;
		}
		return count;
	}

	/**
	 * 查找一条数据(包含录音文件数据list)
	 * @param mediaId
	 * @return
	 */
	public synchronized RecorderInfo findInfoByMediaId(String mediaId) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		RecorderInfo info = null;
		Cursor c = db.query(DBConstants.TABLE_RECORDING, null, DBConstants.REC_MEDIA_ID+"=?",
				new String[]{mediaId}, null, null,null);
		if(c != null && c.moveToFirst()){
			String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
			File file = new File(Constants.RECORDING_PATH, time+".mp3");
			if(file.exists()){
				String etime = c.getString(c.getColumnIndex(DBConstants.REC_END_TIME));
				if(!StringUtil.isNull(etime)){
					info = new RecorderInfo();
					int reason = c.getInt(c.getColumnIndex(DBConstants.REC_REASON));
					info.setReason(reason);
					info.setMediaId(mediaId);
					info.setTime(time);
					int slat = c.getInt(c.getColumnIndex(DBConstants.REC_START_LAT));
					int slng = c.getInt(c.getColumnIndex(DBConstants.REC_START_LNG));
					int elat = c.getInt(c.getColumnIndex(DBConstants.REC_END_LAT));
					int elng = c.getInt(c.getColumnIndex(DBConstants.REC_END_LNG));
					info.setEtime(etime);
					info.setsLat(slat);
					info.setsLng(slng);
					info.seteLat(elat);
					info.seteLng(elng);
					info.setSize(128+FileOper.getFileSize(file));
					/**查找数据*/
					ArrayList<byte[]> listData = FileOper.file2ByteList(file);
					info.setListData(listData);
				}
			}
		}
		db.close();
		return info;
	}

	/**
	 * 删除一条数据
	 * @param mediaId
	 * @return
	 */
	public synchronized int deleteInfo(RecorderInfo info) {
		// TODO Auto-generated method stub
		deletePhoto(info.getTime());
		SQLiteDatabase db = helper.getWritableDatabase();
		int result = deleteInfo(db, info.getMediaId());
		db.close();
		return result;
	}

	/*	*//**
	 * 删除照片
	 *//*
	public static void deletePhoto(PhotoInfo info){
		deletePhoto(info.getTime());
	}*/

	/**
	 * 删除照片
	 */
	public static void deletePhoto(String fileName){
		File file = new File(Constants.RECORDING_PATH, fileName+".mp3");
		if(file.exists()){
			file.delete();
		}
	}

	/**
	 * 删除一条数据
	 * @param db
	 * @param mediaId
	 * @return
	 */
	private synchronized int deleteInfo(SQLiteDatabase db, String mediaId) {
		// TODO Auto-generated method stub
		int result = -1;
		Cursor c = db.query(DBConstants.TABLE_RECORDING, null, DBConstants.REC_MEDIA_ID+"=?",
				new String[]{mediaId}, null, null,null);
		if(c != null && c.moveToFirst()){
			int id = c.getInt(c.getColumnIndex(DBConstants.REC_ID));
			result = db.delete(DBConstants.TABLE_RECORDING,
					DBConstants.REC_ID+"=?", new String[]{String.valueOf(id)});
		}
		AppLog.i(TAG, "删除一条录音数据，result:"+result);
		return result;
	}

	/**
	 * 获取录音信息列表（不包含数据）
	 * @param reason
	 * @param sTime
	 * @param eTime
	 * @return
	 */
	public synchronized ArrayList<RecorderInfo> findInfos(int reason, String sTime,
														  String eTime) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		ArrayList<RecorderInfo> infos = null;
		Cursor c;
		if(reason == -1){
			c = db.query(DBConstants.TABLE_RECORDING, null, null, null, null, null,DBConstants.REC_TIME+" desc");
		}else{
			c = db.query(DBConstants.TABLE_RECORDING, null, DBConstants.REC_REASON+"=?",
					new String[]{String.valueOf(reason)}, null, null,DBConstants.REC_TIME+" desc");
		}
		if(c != null){
			// 是否需要时间筛选
			boolean select = false;
			AppLog.i(TAG, "筛选录音数据sTime:"+sTime+"; eTime:"+eTime);
			long sTimeCode = Long.parseLong(sTime);
			long eTimeCode = Long.parseLong(eTime);
			if(sTimeCode != 0 && eTimeCode != 0){
				select = true;
			}
			infos = new ArrayList<RecorderInfo>();
			while(c.moveToNext()){
				if(select){
					String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
					boolean isPassed = DateUtil.isBetweenDate1AndDate2(DateUtil.df8, sTime, eTime, time);
					if(isPassed){
						RecorderInfo info = new RecorderInfo();
						String mediaId = c.getString(c.getColumnIndex(DBConstants.REC_MEDIA_ID));
						File file = new File(Constants.RECORDING_PATH, time+".mp3");
						if(file.exists()){
							String etime = c.getString(c.getColumnIndex(DBConstants.REC_END_TIME));
							if(!StringUtil.isNull(etime)){
								info.setMediaId(mediaId);
								info.setTime(time);
								int slat = c.getInt(c.getColumnIndex(DBConstants.REC_START_LAT));
								int slng = c.getInt(c.getColumnIndex(DBConstants.REC_START_LNG));
								int elat = c.getInt(c.getColumnIndex(DBConstants.REC_END_LAT));
								int elng = c.getInt(c.getColumnIndex(DBConstants.REC_END_LNG));
								info.setsLat(slat);
								info.setsLng(slng);
								info.seteLat(elat);
								info.seteLng(elng);
								info.setEtime(etime);
								info.setReason(c.getInt(c.getColumnIndex(DBConstants.REC_REASON)));
								info.setSize(128+FileOper.getFileSize(file));
								infos.add(info);
							}
						}else{
							db.delete(DBConstants.TABLE_RECORDING, DBConstants.REC_MEDIA_ID+"=?",
									new String[]{mediaId});
						}
					}
				}else{
					RecorderInfo info = new RecorderInfo();
					String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
					String mediaId = c.getString(c.getColumnIndex(DBConstants.REC_MEDIA_ID));
					File file = new File(Constants.RECORDING_PATH, time+".mp3");
					if(file.exists()){
						String etime = c.getString(c.getColumnIndex(DBConstants.REC_END_TIME));
						if(!StringUtil.isNull(etime)){
							info.setMediaId(mediaId);
							info.setTime(time);
							info.setReason(c.getInt(c.getColumnIndex(DBConstants.REC_REASON)));
							int slat = c.getInt(c.getColumnIndex(DBConstants.REC_START_LAT));
							int slng = c.getInt(c.getColumnIndex(DBConstants.REC_START_LNG));
							int elat = c.getInt(c.getColumnIndex(DBConstants.REC_END_LAT));
							int elng = c.getInt(c.getColumnIndex(DBConstants.REC_END_LNG));
							info.setsLat(slat);
							info.setsLng(slng);
							info.seteLat(elat);
							info.seteLng(elng);
							info.setSize(128+FileOper.getFileSize(file));
							infos.add(info);
						}
					}else{
						db.delete(DBConstants.TABLE_RECORDING, DBConstants.REC_MEDIA_ID+"=?",
								new String[]{mediaId});
					}
				}
			}
		}
		db.close();
		return infos;
	}

	/**
	 * 获取录音信息列表（不包含数据）
	 * @param reason
	 * @param sTime
	 * @param eTime
	 * @return
	 */
	public synchronized ArrayList<RecorderInfo> findInfos() {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		ArrayList<RecorderInfo> infos = null;
		Cursor c = db.query(DBConstants.TABLE_RECORDING, null, null, null, null, null,null);
		if(c != null){
			infos = new ArrayList<RecorderInfo>();
			while(c.moveToNext()){
				RecorderInfo info = new RecorderInfo();
				String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
				String mediaId = c.getString(c.getColumnIndex(DBConstants.REC_MEDIA_ID));
				File file = new File(Constants.RECORDING_PATH, time+".mp3");
				if(file.exists()){
					String etime = c.getString(c.getColumnIndex(DBConstants.REC_END_TIME));
					info.setMediaId(mediaId);
					info.setTime(time);
					info.setReason(c.getInt(c.getColumnIndex(DBConstants.REC_REASON)));
					int slat = c.getInt(c.getColumnIndex(DBConstants.REC_START_LAT));
					int slng = c.getInt(c.getColumnIndex(DBConstants.REC_START_LNG));
					int elat = c.getInt(c.getColumnIndex(DBConstants.REC_END_LAT));
					int elng = c.getInt(c.getColumnIndex(DBConstants.REC_END_LNG));
					info.setsLat(slat);
					info.setsLng(slng);
					info.seteLat(elat);
					info.seteLng(elng);
					info.setSize(128+FileOper.getFileSize(file));
					infos.add(info);
					System.out.println("录音:"+"time:"+time+"; etime"+etime+"; mediaId:"+mediaId+"; size"+info.getSize());
				}else{
					db.delete(DBConstants.TABLE_RECORDING, DBConstants.REC_MEDIA_ID+"=?",
							new String[]{mediaId});
				}
			}
		}
		db.close();
		return infos;
	}

	public synchronized int updateLastEndTime() {
		// TODO Auto-generated method stub
		int result = -1;
		try {
			SQLiteDatabase db = helper.getWritableDatabase();
			result = updateLastEndTime(db);
			db.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
		return result;
	}

	public synchronized int updateLastEndTime(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		int result = -1;
		try {
			Cursor c = db.query(DBConstants.TABLE_RECORDING, null, null, null, null, null,null);
			if(c != null && c.moveToLast()){
				String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
				String mediaId = c.getString(c.getColumnIndex(DBConstants.REC_MEDIA_ID));
				File file = new File(Constants.RECORDING_PATH, time+".mp3");
				//AppLog.i(TAG, "录音时间更新:"+file.getAbsolutePath()+":"+file.exists());
				if(file.exists()){
					String etime = c.getString(c.getColumnIndex(DBConstants.REC_END_TIME));
					if(StringUtil.isNull(etime)){
						values.clear();
						values.put(DBConstants.REC_END_TIME, DateUtil.getTodayDate(DateUtil.df6));
						values.put(DBConstants.REC_END_LAT, EncoderUtil.getCurretnLat());
						values.put(DBConstants.REC_END_LNG, EncoderUtil.getCurretnLng());
						result = db.update(DBConstants.TABLE_RECORDING, values, DBConstants.REC_MEDIA_ID+"=?", new String[]{String.valueOf(mediaId)});
						AppLog.i(TAG, "录音时间更新result:"+result);
					}
				}else{
					result = db.delete(DBConstants.TABLE_RECORDING, DBConstants.REC_MEDIA_ID+"=?",
							new String[]{mediaId});
					AppLog.i(TAG, "录音删除result:"+result);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
		return result;
	}

	public synchronized int updateReason(int reason) {
		// TODO Auto-generated method stub
		int result = -1;
		SQLiteDatabase db = helper.getWritableDatabase();
		try {
			Cursor c = db.query(DBConstants.TABLE_RECORDING, null, null, null, null, null,null);
			if(c != null && c.moveToLast()){
				String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
				String mediaId = c.getString(c.getColumnIndex(DBConstants.REC_MEDIA_ID));
				File file = new File(Constants.RECORDING_PATH, time+".mp3");
				if(file.exists()){
					values.clear();
					values.put(DBConstants.REC_REASON, reason);
					result = db.update(DBConstants.TABLE_RECORDING, values, DBConstants.REC_MEDIA_ID+"=?", new String[]{String.valueOf(mediaId)});
				}else{
					db.delete(DBConstants.TABLE_RECORDING, DBConstants.REC_MEDIA_ID+"=?",
							new String[]{mediaId});
				}
			}
			db.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			AppLog.e(ExceptionUtil.getInfo(e), e);
		}
		return result;
	}

	public synchronized int updateReason(ArrayList<String> mediaIdList) {
		// TODO Auto-generated method stub
		int result = -1;
		if(mediaIdList != null && mediaIdList.size() > 0){
			SQLiteDatabase db = helper.getWritableDatabase();
			try {
				db.beginTransaction();
				for(int i = 0;i<mediaIdList.size();i++){
					String mediaId = mediaIdList.get(i);
					AppLog.i(TAG, "录音：updateReason,mediaId:"+mediaId);

					Cursor c = db.query(DBConstants.TABLE_RECORDING, null, DBConstants.REC_MEDIA_ID+"=?", new String[]{mediaId}, null, null,null);
					if(c != null && c.moveToFirst()){
						String time = c.getString(c.getColumnIndex(DBConstants.REC_TIME));
						File file = new File(Constants.RECORDING_PATH, time+".mp3");
						if(file.exists()){
							values.clear();
							values.put(DBConstants.REC_REASON, 1);
							result = db.update(DBConstants.TABLE_RECORDING, values, DBConstants.REC_MEDIA_ID+"=?", new String[]{String.valueOf(mediaId)});
							AppLog.i(TAG, "录音：updateReason,mediaId:"+mediaId+"; result:"+result);
						}else{
							db.delete(DBConstants.TABLE_RECORDING, DBConstants.REC_MEDIA_ID+"=?",
									new String[]{mediaId});
						}
					}
				}
				//设置事务标志为成功，当结束事务时就会提交事务
				db.setTransactionSuccessful();
				db.endTransaction();
				db.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				AppLog.e(ExceptionUtil.getInfo(e), e);
			}
		}
		return result;
	}
}
